package com.japp.sys.service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.japp.base.BaseService;
import com.japp.sys.bean.SelectBean;
import com.japp.sys.bean.UserBean;
import com.japp.sys.mapper.DpMapper;
import com.japp.sys.mapper.RoleMapper;
import com.japp.sys.mapper.UserMapper;
import com.japp.tools.common.JappLog;
import com.japp.tools.page.Page;

@Service
@Transactional(rollbackFor = Exception.class)
public class UserService implements BaseService{

	@Autowired
	private UserMapper userMapper;	
	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private DpMapper dpMapper;

	
	/**
	 * 分页查询
	 * @param page
	 * @param obj
	 * @return
	 */
	public Page<UserBean> getPage(Page<UserBean> page,UserBean obj){
		try {

			return userMapper.getPage(page, obj);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public UserBean findUserById(int userid){
		return userMapper.findUserById(userid);
	}
	
	public int updateUser(UserBean user){
		int rel = 0;
		try {
			rel = userMapper.updateUser(user);
		} catch (Exception e) {
			e.printStackTrace();
			if(e.getCause().getMessage().indexOf("违反唯一约束")!=-1){
				rel = 999;
				return rel;
			}
			rel = 0;
		}
		return rel;
	}

	public UserBean findUserByIdAndPwd(UserBean user) {
		UserBean users;
		try {
			users = userMapper.findUserByIdAndPwd(user);
			return users;
		} catch (Exception e) {
			JappLog.log.error("",e);
		}
		return null;
	}

	public int insertUser(UserBean user) {
		int rel = 0;
		try{
			rel = userMapper.insertUser(user);
		} catch (Exception e) {
			if(e.getCause().getMessage().indexOf("违反唯一约束")!=-1){
				rel = 999;
				return rel;
			}
			rel = 0;
		}
		return rel;
	}

	public int deleteUser(String[] keys) {
		// TODO Auto-generated method stub
		if(!(keys!=null&&keys.length>0)){
			return 0;
		}
		return userMapper.deleteUser(keys);
	}
	public Map<String,String> getRAndDAll(){
		Map<String, String> mapstr = new HashMap<String, String>();
		String json = "";
		List<SelectBean> liseb = roleMapper.queryRoleSelectAll();	//角色
		List<SelectBean> listd = dpMapper.queryDpSelectAll();		//部门
		if(liseb!=null&&liseb.size()>0){
			json = JSONArray.fromObject(liseb).toString();
			json = "{\"list\":"+json+"}";
		}else{
			json = "{\"list\":[{value:\"-1\",key:\"无\"}]}";
		}
		mapstr.put("liseb", json);
		if(listd!=null&&listd.size()>0){
			json = JSONArray.fromObject(listd).toString();
			json = "{\"list\":"+json+"}";
		}else{
			json = "{\"list\":[{value:\"-1\",key:\"无\"}]}";
		}
		mapstr.put("listd", json);
		return mapstr;
	}
	
}
